import { addApp } from '@/apis/appApi'
import { ConversationsContext } from '@/context'
import { selectUserId, selectUserName } from '@/stores'
import { Sender } from '@ant-design/x'
import { message } from 'antd'
import { useContext, useState } from 'react'
import { useNavigate, useParams } from 'react-router'

export const Add = () => {
  const [userInput, setUserInput] = useState('')
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const userId = selectUserId()
  const { loadConversions } = useContext(ConversationsContext)
  const userName = selectUserName()
  const params = useParams()
  const handelSendMessage = async () => {
    if (!userInput.trim()) {
      message.warning('请输入应用描述')
      return
    }
    if (!userId) {
      message.warning('请先登录')
      navigate('/user/login')
      return
    }
    setLoading(true)
    const res = await addApp({
      initPrompt: userInput,
    })
    try {
      if (res.data.code === 0 && res.data.data) {
        setUserInput('')
        message.success('发送成功!')
        loadConversions()
        const convId = String(res.data.data)
        navigate({
          pathname: `/app/chat/${convId}`,
          search: `?roleType=${params?.id}`,
        })
      } else {
        message.error('创建失败：' + res.data.message)
      }
    } catch (error) {
      message.error('创建失败：' + error)
    } finally {
      setLoading(false)
    }
  }
  return (
    <div className="h-screen w-full relative flex flex-col gap-8 items-center justify-center">
      <div className="mx-auto flex w-full flex-col items-center gap-7 max-md:pt-4 max-w-2xl">
        <div className="text-[40px]">你好, {userName}</div>
      </div>
      <div className="top-5 z-10 mx-auto w-full max-w-2xl">
        <Sender
          onSubmit={handelSendMessage}
          onCancel={() => {
            setLoading(false)
            message.error('Cancel sending!')
          }}
          loading={loading}
          onChange={setUserInput}
        />
      </div>
    </div>
  )
}
